//
//  BHCircleMainViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/4.
//

import UIKit

class BHCircleMainViewController: BHBaseViewController {
    
    lazy var firstGuideView: BHCircleGuideChoseView = {
        let view = BHCircleGuideChoseView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height-UIScreen.safeBottomHeight-49)
        view.delegate = self
        return view
    }()
    
    lazy var searchBarView: BHCircleSearchBarView = {
        let view = BHCircleSearchBarView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.begainY)
        return view
    }()
    
    
    lazy var pageCycleView: CZPageView = {
        let view = CZPageView.init(frame: CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: 45))
        view.backgroundColor = .white
        view.delegate = self
        let config = CZPageConfig.init()
        config.showLine = true
        config.lineSize = CGSize(width: 20, height: 4)
        config.lineRadius = 2
        config.lineColor = .color_34CE98
        config.nomalFont = .systemFont(ofSize: 14, weight: .medium)
        config.selectFont = .systemFont(ofSize: 14, weight: .bold)
        config.nomalColor = .color_666666
        config.selectColor = .color_34CE98
        config.itemSpace = 20
        config.leadingSpace = 15
        config.tralingSpace = 50
        
        view.config = config
        return view
    }()
    
    lazy var bigScrollView: UIScrollView = {
        let view = UIScrollView.init()
        view.frame = CGRect(x: 0, y: UIScreen.begainY+45, width: UIScreen.width, height: UIScreen.height-UIScreen.begainY-45-UIScreen.safeBottomHeight-49)
        view.isPagingEnabled = true
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.bounces = false
        view.rebuild()
        view.isScrollEnabled = false
        return view
    }()
    
    lazy var childEditeView: BHCircleClassShowView = {
        let view = BHCircleClassShowView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-UIScreen.safeBottomHeight-49)
        view.delegate = self
        return view
    }()
    
    lazy var serviceManager: BHCircleServiceManager = {
        let manager = BHCircleServiceManager.init()
        return manager
    }()
    
    fileprivate var childrenVC: BHCircleChildViewController!
    fileprivate var childrenArray: [BHCircleChildViewController] = []
    
    // 个人栏目
    fileprivate var userColumnArray: [BHCircleColumnModel] = []
    fileprivate var regularColumnArray: [BHCircleColumnModel] = []
    fileprivate var moveColumnArray: [BHCircleColumnModel] = []
    fileprivate var bindColumnArray: [BHCircleColumnModel] = []


    
    lazy var flagClassBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: UIScreen.width-50, y: UIScreen.begainY, width: 50, height: 45)
        btn.setImage(UIImage.init(named: "bh_circle_class_arrow_down"), for: .normal)
        btn.addTarget(self, action: #selector(closeOrFlagClassAct), for: .touchUpInside)
        btn.backgroundColor = .white
        return btn
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.regularColumnArray.count == 0 {
            self.serviceManager.requestColumnService()
        }
        if self.userColumnArray.count == 0 {
            self.serviceManager.requestSelfColumnService()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.bh_navigationBar.removeFromSuperview()
        
        
        self.view.addSubview(self.searchBarView)
        self.view.addSubview(self.pageCycleView)
        self.view.addSubview(self.flagClassBtn)
        self.view.addSubview(self.bigScrollView)
        
        self.view.addSubview(self.childEditeView)
        
        self.searchBarView.begainAddMoreCircle = {[weak self] in
            let vc = BHCircleChoseImageOrVideoViewController.init()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        
        self.oberserveNetResponse()
        
        let cache = BHCache_UserDefault.load_circleChose()
        if cache == 1 { // 已经选过了
            self.serviceManager.requestSelfColumnService()
        }
        self.serviceManager.requestColumnService()
        
        // 搜索
        self.searchBarView.goSearchBlock = { [unowned self] text in
            self.childrenVC.searchKey = text
            
        }
        
    }
    @objc func closeOrFlagClassAct() {
        self.childEditeView.show()
    }
}

extension BHCircleMainViewController {
    func configCircleVC()  {
        for view in self.bigScrollView.subviews {
            view.removeFromSuperview()
        }
        if self.childrenArray.count != 0 {
            self.childrenArray.removeAll()
        }
       
        
        self.pageCycleView.itemArray = BHCircleManager.transColumnModel(array: self.userColumnArray)
        self.pageCycleView.relationScrollView = self.bigScrollView
        for (index,model) in self.userColumnArray.enumerated() {
            let vc = BHCircleChildViewController.init()
            vc.columnId = model.columnId
            self.childrenArray.append(vc)
            self.bigScrollView.addSubview(vc.view)
            vc.view.mas_makeConstraints { (make) in
                make?.top.mas_equalTo()(self.bigScrollView)
                make?.left.mas_equalTo()(CGFloat(index)*UIScreen.width)
                make?.width.mas_equalTo()(UIScreen.width)
                make?.height.mas_equalTo()(self.bigScrollView)
            }
            if index == 0 {
                self.childrenVC = vc
                self.childrenVC.refreshColumnService()
            }
        }
        self.bigScrollView.contentSize = CGSize(width: UIScreen.width*CGFloat(self.userColumnArray.count), height: 0)
        self.pageCycleView.current = 0
        self.bigScrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        self.bigScrollView.alwaysBounceVertical = false;
        
    }
}

extension BHCircleMainViewController: BHCircleClassShowViewDelegate {
    func didSelectColumn(model: BHCircleColumnModel, index: Int) {
        // 第一栏有个推荐，所以后面的都要+1
        self.pageCycleView.current = index+1
    }
    
    func editeColumnComplete(array: [BHCircleColumnModel]) {
        var temp: [String] = []
        for model in array {
            temp.append(model.columnId)
        }
        self.bindColumnArray = array
        self.serviceManager.bindColumnService(columnIdArray: temp)
    }
}

extension BHCircleMainViewController: CZPageViewDelegate {
    func pageViewSelectdIndex(_ index: Int, with model: CZTopSegMentItemModel, with pageView: CZPageView) {
        self.childrenVC = self.childrenArray[index]
        self.searchBarView.search_textFiled.text = self.childrenVC.searchKey
        self.childrenVC.refreshColumnService()
        
    }
}


extension BHCircleMainViewController: BHCircleGuideChoseViewDelegate {
    func didGuideViewSelectIndexType(index: Int,columnIds: [Int:String]) {
        if index == 0 { // 跳过
            self.firstGuideView.isHidden  = true
            SVProgressHUD.show()
            self.serviceManager.bindColumnService(columnIdArray: [])
        }else {
            let idArray = Array(columnIds.values) as [String]
            SVProgressHUD.show()
            self.serviceManager.bindColumnService(columnIdArray: idArray)
        }
    }
}

extension BHCircleMainViewController {
    func oberserveNetResponse()  {
        // 返回固定栏目和非固定栏目
        self.serviceManager.circleColumnResponseForBlock = { [weak self] (regularArray,moveArray,bindArray) in
            self?.regularColumnArray = regularArray
            self?.moveColumnArray = moveArray
            self?.bindColumnArray = bindArray
            
            self?.childEditeView.allColumnArray = regularArray
            self?.childEditeView.moreColumnArray = moveArray
            self?.childEditeView.tempEditeArray = bindArray
            
            let cache = BHCache_UserDefault.load_circleChose()
            if cache != 1 { // 没有选过了
                self?.firstGuideView.columnArray = self?.moveColumnArray ?? []
                self?.view.addSubview(self!.firstGuideView)
            }
            BHCache_UserDefault.save_circleChose()
        }
        
        // 返回个人栏目
        self.serviceManager.circleColumnResponseForUserBlock = { [weak self] userColumnArray in
            self?.userColumnArray = userColumnArray
            let model = BHCircleColumnModel.init()
            model.name = "推荐"
            model.columnId = "推荐"
            self?.userColumnArray.insert(model, at: 0)
            // 重新布局
            self?.configCircleVC()
        }
        
        // 绑定栏目
        self.serviceManager.circleBindColumnHandler = { [weak self] (success,errorMsg,columnIdArray) in
            SVProgressHUD.dismiss()
            if success { // 获取用户栏目
                self?.serviceManager.requestSelfColumnService()
                if self?.firstGuideView != nil && self?.firstGuideView.superview != nil {
                    self?.firstGuideView.removeFromSuperview()
                }
            }else {
                BHToast.toast(text: errorMsg) 
            }
        }
    }
}

